package com.sm.imlibrary.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.sm.imlibrary.Constants;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * created by zhud on 2019/8/14
 */
public class HttpIMCallback<T extends IMBaseBean> implements Callback<T> {

    public HttpIMCallback() {
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        String message = response.message();
        Gson gson = new GsonBuilder().serializeNulls().create();
        try {
            T data = response.body();
            gson.toJson(data);
            if (data.getCode() == Constants.SUCCEED_CODE) {
                onSuccess(data);
                onResponse(message);
            } else if (data.getCode() == Constants.OVERDUE_CODE) {
                //过期登录信息
                onFail(data.getCode());
            } else {
                //请求失败
                onFail(data.getCode());
            }
        } catch (JsonSyntaxException e) {
            onFail(Constants.FAIL_CODE);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        onFail(Constants.FAIL_CODE);
    }

    //请求失败后的 默认回调
    protected void onFail(int code) {

    }

    //请求成功 返回/数据源字符
    protected void onResponse(String data) {

    }

    //请求成功 返回
    protected void onSuccess(T data) {

    }
}
